package com.jianhua.appmarket.module.service.system.impl;

import com.jianhua.appmarket.common.util.SnowflakeKeyUtil;
import com.jianhua.appmarket.module.dao.system.OrgDao;
import com.jianhua.appmarket.module.dao.system.OrgUserDao;
import com.jianhua.appmarket.module.entity.system.Org;
import com.jianhua.appmarket.module.entity.system.User;
import com.jianhua.appmarket.module.model.system.OrgParam;
import com.jianhua.appmarket.module.model.system.OrgUserParam;
import com.jianhua.appmarket.module.model.system.OrgVO;
import com.jianhua.appmarket.module.model.system.UserVO;
import com.jianhua.appmarket.module.service.system.IOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class OrgService implements IOrgService {

    @Autowired
    private OrgDao orgDao;
    @Autowired
    private OrgUserDao orgUserDao;

    @Override
    public List<OrgVO> listOrgsTree(OrgParam param, User user) {
        param.setUserId(user.getId() == 0L ? null : user.getId());//userId =0 代表是超级管理员
        long parentId = (user.getId() == 0L ? -1L : param.getParentId());
        param.setParentId(parentId);
        List<OrgVO> vos = orgDao.listByParam(param);
        vos.forEach(menu -> {
            param.setParentId(menu.getId());
            param.setUserId(null);
            menu.setChildren(orgDao.listByParentId(param));
        });
        return vos;
    }

    @Override
    public List<OrgVO> listBranchByParentId(Long parentId, User user) {
        OrgParam param = new OrgParam();
        param.setUserId(user.getId() == 0L ? null : user.getId());//userId =0 代表是超级管理员
        param.setParentId(parentId);
        return orgDao.listByParentId(param);
    }

    @Override
    @Transactional
    public Boolean addOrEditOrg(Org org, UserVO user) {
        org.setUpdateUser(user.getNickName());
        if(Objects.isNull(org.getId())){
            org.setId(SnowflakeKeyUtil.generateId());
            org.setCreateUser(user.getNickName());
            return orgDao.insert(org) > 0;
        }else {
            return editOrg(org);
        }
    }

    @Override
    public Boolean editOrg(Org org) {
        return orgDao.update(org) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteOrg(Long orgId) {
        OrgUserParam param = new OrgUserParam();
        param.setOrgId(orgId);
        return orgDao.deleteById(orgId) > 0 && orgUserDao.deleteByParam(param) > 0;
    }
}
